<template>
  <div>
    <a-cascader
      v-model:value="gradeAndClass"
      multiple
      :options="sectionList"
      placeholder="请选择"
      allow-clear
      :load-data="onLoadDataGradeClass"
      :max-tag-count="1"
      :field-names="{ label: 'name', value: 'id' }"
      dropdown-class-name="micro-dormitory-grade-and-class"
      class="my-grade-and-class"
      :open="gradeAndClassOpen"
      :get-popup-container="
        triggerNode => {
          return triggerNode.parentNode;
        }
      "
      @click.stop="gradeAndClassOpen = true"
      @change="onChangeGradeAndClass"
    >
      <template #tagRender>
        <Tooltip
          :overlay-style="{ whiteSpace: 'normal', width: '300px' }"
          :get-popup-container="
            triggerNode => {
              return triggerNode.parentNode || document.body;
            }
          "
          placement="topLeft"
          :title="gradeAndClassText"
          @click.stop="gradeAndClassTip"
        >
          <p class="descriptionsItemStyle">{{ gradeAndClassText }}</p>
        </Tooltip>
      </template>
    </a-cascader>
  </div>
</template>

<script setup>
import { Tooltip } from 'ant-design-vue';
import { ref, nextTick, onMounted, defineExpose, computed, onBeforeUnmount } from 'vue';
import { classList, getSectionCodeList, gradeListNew, getSectionCodeClassIds } from '@/api/common';
import { getRgba } from '@/utils/validate.js';
import { useStore } from 'vuex';
const store = useStore();
let stateUser = ref({});
onMounted(async () => {
  setTimeout(() => {
    stateUser.value = JSON.parse(localStorage.getItem('STATE_USER'));
    console.log(stateUser.value);
    getSection();
  }, 500);

  nextTick(() => {
    document.body.onclick = () => {
      gradeAndClassOpen.value ? (gradeAndClassOpen.value = false) : '';
    };
  });
});
// 学段list
const sectionList = ref([]);
const gradeAndClass = ref('');
// 获取学段
const getSection = () => {
  console.log(stateUser.value, '----stateUser');
  if (
    localStorage.dormitoryClassInfoQuery ||
    localStorage.classCollectiveQuery ||
    localStorage.dormitoryUserQuery
  ) {
    return;
  }
  sectionList.value = stateUser.value.sectionList;
  console.log(sectionList.value, 'sectionList.value');
  // getSectionCodeList().then(async res => {
  //   // console.log('获取学段的res', res);
  //   if (res.data.code === 200) {
  //     let list = res.data.data;
  //     sectionList.value = list;
  //     sectionList.value.forEach(item => {
  //       item.name = item.sectionName;
  //       item.id = item.sectionCode;
  //       item.isLeaf = false;
  //     });
  //   }
  // });
};
// 选择年纪/班级异步动态加载
const onLoadDataGradeClass = selectedOptions => {
  // console.log(selectedOptions, 'selectedOptions');
  const targetOption = selectedOptions[selectedOptions.length - 1];
  // console.log(selectedOptions, '222');
  targetOption.loading = true; // load options lazily
  // 获取年级
  if (targetOption.sectionCode && !targetOption.children) {
    console.log('走的这里吗？？？？？？11111111111');
    gradeListNew(targetOption.sectionCode).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        // console.log(res.data, 'res.data');
        targetOption.children = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: elem.gradeName,
            id: elem.gradeId,
            isLeaf: false
          };
          targetOption.children.push(obj);
        });
        sectionList.value = [...sectionList.value];
      }
    });
  }
  // 获取班级
  if (!targetOption.sectionCode && !targetOption.children) {
    // console.log(selectedOptions);
    let id = targetOption.id;
    classList({ gradeId: id }).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        targetOption.children = [];
        let classIds = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: elem.className,
            id: elem.classId,
            isLeaf: true
          };
          classIds.push(elem.classId);
          targetOption.children.push(obj);
        });
        targetOption.classIds = classIds;
        sectionList.value = [...sectionList.value];
      }
    });
  }
  // console.log('------======', optionList.value.roomList);
};

// 选择年纪/班级 回调
const onChangeGradeAndClass = (value, selectedOptions) => {
  // console.log(value, selectedOptions, 'iii');
  let data = [];
  selectedOptions.forEach(item => {
    // console.log(item, '2222');
    let str = '';
    item.forEach(itemChild => {
      str += itemChild.name;
    });
    // 获取学段下的所有classIds
    if (item.length === 1 && !item[0].classIds) {
      // console.log(item.length === 1, 'item.length === 1');
      getSectionCodeClassIds(item[0].sectionCode).then(res => {
        if (res.data.code === 200) {
          let index = sectionList.value.findIndex(
            itemSection => itemSection.sectionCode === item[0].sectionCode
          );
          // console.log(index, 'index');
          if (res.data.data.length === 1 && res.data.data[0] === -1) {
            index !== -1 ? (sectionList.value[index].classIds = []) : '';
          } else {
            index !== -1 ? (sectionList.value[index].classIds = res.data.data) : '';
          }
        }
        console.log(sectionList.value);
      });
    } else if (item.length === 2 && !item[1].classIds) {
      let index = -1;
      let indexChild = -1;
      // console.log(item.length === 2, 'item.length === 2');
      sectionList.value.forEach((itemSection, indexSection) => {
        if (itemSection.sectionCode === item[0].sectionCode) {
          index = indexSection;
          indexChild = itemSection.children.findIndex(itemGrasd => itemGrasd.id === item[1].id);
        }
      });
      // console.log(index, indexChild);
      if (index !== -1 && indexChild !== -1) {
        classList({ gradeId: sectionList.value[index].children[indexChild].id }).then(res => {
          if (res.data.code === 200) {
            sectionList.value[index].children[indexChild].children = [];
            let classIds = [];
            res.data.data.forEach(elem => {
              let obj = {
                name: elem.className,
                id: elem.classId,
                isLeaf: true
              };
              classIds.push(elem.classId);
              sectionList.value[index].children[indexChild].children.push(obj);
            });
            sectionList.value[index].children[indexChild].classIds = classIds;
          }
        });
      }
    }

    data.push(str);
  });
  gradeAndClassText.value = data.join('/');
  // console.log(where.value.gradeAndClassText);
  // where.value.gradeAndClass = data;
  // console.log(where.value.gradeAndClass, 'where.value.gradeAndClass ');
  // console.log(value, selectedOptions, '选择年纪/班级');
};
const gradeAndClassText = ref('');
// 选择学段/年纪/班级 打开下拉
const gradeAndClassOpen = ref(false);
const gradeAndClassTip = () => {
  nextTick(() => {
    gradeAndClassOpen.value = !gradeAndClassOpen.value;
  });
};
// 处理学段年级班级三级筛选数据
const disposeChangeData = () => {
  let gradeAndClassNew = [];
  if (gradeAndClass.value) {
    gradeAndClass.value.forEach(item => {
      let index = sectionList.value.findIndex(itemChild => itemChild.sectionCode === item[0]);
      if (item.length === 1) {
        if (index !== -1 && sectionList.value[index].classIds) {
          gradeAndClassNew = [...gradeAndClassNew, ...sectionList.value[index].classIds];
        }
      } else if (item.length === 2 && index !== -1) {
        let indexChild = sectionList.value[index].children.findIndex(
          itemChild => itemChild.id === item[1]
        );
        if (indexChild !== -1 && sectionList.value[index].children[indexChild].classIds) {
          gradeAndClassNew = [
            ...gradeAndClassNew,
            ...sectionList.value[index].children[indexChild].classIds
          ];
        }
      } else if (item.length === 3) {
        gradeAndClassNew = [...gradeAndClassNew, item[2]];
      }
    });
  }
  // 如果已选择 但是 班级id为空 则传 -1
  if (gradeAndClass.value.length && gradeAndClassNew.length === 0) {
    gradeAndClassNew = [-1];
  }
  console.log(gradeAndClassNew, '???????????');
  return gradeAndClassNew;
};
const setPrimaryColor = computed(() => store.state.user.primaryColor);
const backgroundColorValue = computed(() => getRgba(store.state.user.primaryColor, 0.1));
defineExpose({
  gradeAndClassOpen,
  sectionList,
  gradeAndClass,
  disposeChangeData,
  gradeAndClassText
});
onBeforeUnmount(() => {
  document.body.onclick = () => {};
});
</script>

<style lang="less" scoped>
/deep/.micro-dormitory-cascader-menu-item-content,
/deep/.micro-dormitory-cascader-menu-item,
/deep/.micro-dormitory-cascader-menu-item-expand {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  width: 270px !important;
}

:deep(.micro-dormitory-grade-and-class) {
  max-width: 434px;
  .micro-dormitory-cascader-menu {
    overflow-x: hidden;
    min-width: 144px;
    max-width: 254px;
    .micro-dormitory-cascader-menu-item {
      width: auto !important;
    }
  }
  .micro-dormitory-cascader-checkbox-inner {
    border-radius: 2px;
  }
  .micro-dormitory-cascader-menu-item {
    padding: 5px 8px;
  }
  .micro-dormitory-cascader-menu-item:hover {
    background-color: transparent;
    color: v-bind(setPrimaryColor);
  }
  .micro-dormitory-cascader-menu-item-active {
    color: v-bind(setPrimaryColor);
    background-color: v-bind(backgroundColorValue) !important;
  }
  .micro-dormitory-cascader-checkbox-indeterminate {
    .micro-dormitory-cascader-checkbox-inner {
      border-color: v-bind(setPrimaryColor);
    }
  }

  // .micro-dormitory-cascader-menus .micro-dormitory-cascader-menu:first-child {
  //   .micro-dormitory-cascader-menu-item-active {
  //     .micro-dormitory-cascader-checkbox-inner {
  //       border-radius: 50%;
  //     }
  //     .micro-dormitory-cascader-checkbox-inner::after,
  //     .micro-dormitory-cascader-menu-item-expand::after {
  //       border: 0 !important;
  //       display: block !important;
  //       width: 16px !important;
  //       height: 16px !important;
  //       margin-top: -8px !important;
  //       margin-left: -8px !important;
  //       background-color: v-bind(setPrimaryColor) !important;
  //       border-top: 0 !important;
  //       border-left: 0 !important;
  //       border-radius: 16px !important;
  //       top: 50% !important;
  //       left: 50% !important;
  //       transform: scale(0.5) !important;
  //       opacity: 1 !important;
  //       transition: all 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86) !important;
  //     }
  //   }
  //   .micro-dormitory-cascader-menu-item {
  //     .micro-dormitory-cascader-checkbox-inner {
  //       border-radius: 50%;
  //     }
  //     .micro-dormitory-cascader-checkbox-checked .micro-dormitory-cascader-checkbox-inner {
  //       background-color: #fff !important;
  //       border: 1px solid #d9d9d9 !important;
  //     }
  //   }
  // }
}
:deep(.my-grade-and-class) {
  .micro-dormitory-select-selection-overflow-item-rest,
  .micro-dormitory-select-selection-overflow-item-suffix {
    display: none;
  }
  .micro-dormitory-select-selection-overflow {
    flex-wrap: nowrap;
  }
  .micro-dormitory-select-selection-overflow-item:first-child {
    width: 230px;
  }
  .descriptionsItemStyle {
    width: 90%;
    margin-left: 10px;
  }
  .micro-dormitory-tooltip-inner {
    max-width: 100%;
  }
}
.descriptionsItemStyle {
  width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin: auto 0;
}
</style>
